
let express = require("express")
let router = express.Router()
let bodyParser = require('body-parser')
let urlencodedParser = bodyParser.urlencoded({ extended: false })   //post请求(转码解析)
let db = require("../db")
let md5 = require("md5-nodejs")

// 通过loginKey 和 loginName 获取用户信息
router.post("/login-msg", urlencodedParser, async (req, res) => {
    const { loginName, loginKey } = req.body
    const sql = `select id,name,age,gender,avatar from users where loginKey='${loginKey}' and loginName='${loginName}'`
    const r = await db.doSQL(sql, [loginName, loginKey])
    if (r.data[0]) {
        res.send(db.handleResults(r.data[0]))
    } else {
        res.send(db.handleNoResults())
    }
})


// 用户登录  -- 拿取token
router.post("/login", urlencodedParser, async (req, res) => {
    const { loginName, loginKey } = req.body
    // console.log(loginName,loginKey)
    const sql = "select id from users where loginName=? and loginKey=?"
    // const sql = `select id from users  where loginKey='${loginKey}'  and  loginName='${loginName}' and status = 1`
    const r = await db.doSQL(sql, [loginName, loginKey])
    // console.log(r.data)
    if (r.data[0]) {    //有id
        const token = await getTokenById(r.data[0].id)
        if (token) {
            res.send(db.handleResults({ token: token }))
        } else {
            // throw error
        }
    } else {    //没找到id
        res.send(db.handleNoResults())
    }
})

// 返回用户角色信息
router.get('/info', async function (req, res) {
    const { token } = req.query;
    const sql = 'select u.id, name, roles, avatar from tokens as t,users as u where t.uid=u.id and t.token=?'
    const r = await db.doSQL(sql, [token])
    // console.log(r);
    if (r.data[0]) {
        res.send(db.handleResults(r.data[0]))
    } else {
        res.send(db.handleNoResults())
    }
})

// 推出登录  删除token
router.post("/logout", urlencodedParser, async (req, res) => {
    let { token } = req.body
    let sql = `delete from tokens where token=?`
    let { data } = await db.doSQL(sql, token)

    if (data.affectedRows == 0) {
        res.send(db.handleError())
    } else {
        res.send(db.handleResults({}))
    }
})

//  获取tonken  
async function getTokenById(uid) {
    const sql = "select * from tokens where uid =?"
    // const sql = `select * from tokens where uid = '${uid}'`
    const r = await db.doSQL(sql, [uid])
    let token
    if (r.data.length == 0) { // 没 token
        let newToken = md5('hyx' + uid + Date.now())
        const sql = "insert into tokens (token, uid) values (?,?)"
        const { data } = await db.doSQL(sql, [newToken, uid])
        if (data.affectedRows == 0) {
            token = null
        } else {
            token = newToken
        }
    } else { // 有 token
        token = r.data[0].token
    }
    return token
}

// 默认导出 相当于 export default
module.exports = router;